package com.xj.jdk17.io;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * MappedByteBuffer 可以将大文件映射到内存中进行操作
 * User: xia
 * Date: 13-10-26
 * Time: 下午8:04
 */
public class FileChannelDemo {
    public void test() throws IOException {
        FileChannel fileChannel = FileChannel.open(Paths.get("D:/xx.txt"), StandardOpenOption.READ,
                StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, 18);
        buffer.put("xiajun".getBytes("utf-8"));
        buffer.force();
        fileChannel.close();
    }

    /**
     * 获取网页内容
     */
    public void getHttpData() throws IOException {
        FileChannel channel = FileChannel.open(Paths.get("D:/xx.txt"), StandardOpenOption.READ,
                StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        InputStream in = new URL("http://www.baidu.com").openStream();
        ReadableByteChannel rbc = Channels.newChannel(in);
        channel.transferFrom(rbc, 0, Integer.MAX_VALUE);
        in.close();
        rbc.close();
        channel.close();
    }

    /*public void tryLock() throws Exception {
        try(FileChannel channel = FileChannel.open(Paths.get("D:/xx.txt"), StandardOpenOption.READ,
                StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);FileLock lock=channel.tryLock()){
            ByteBuffer buffer=ByteBuffer.allocate(64);
            buffer.put("xiajun".getBytes());
            buffer.flip();
            channel.write(buffer);
            Thread.sleep(1000*15);
            lock.release();//释放锁
        }

    }*/

   /* public static void main(String[] args) throws Exception {
        // new FileChannelDemo().test();
        //new FileChannelDemo().getHttpData();
        new FileChannelDemo().tryLock();
    }*/
}
